<?php
/**
 * Created by PhpStorm.
 * User: yys
 * Date: 2016/12/5
 * Time: 17:36
 */

namespace App\Services\TagService;


use App\Services\ImgServices\ImgTool;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\SourcePicService\SourcePicTool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Validator;
class TagService
{
    protected $tagTool;
    protected $imgTool;

    /**
     * TagService constructor.
     */
    public function __construct(TagTool $tagTool,ImgTool $imgTool)
    {
        $this->tagTool=$tagTool;
        $this->imgTool=$imgTool;
    }

    /***
     * 搜索资源标签
     * @param $search
     * @param $app_id
     * @param $type 类型为1时，过滤已绑定具体的资源的标签
     * @param array $where_not_in_tag_ids
     * @return array
     */
    public function searchResourceTagList($search,$app_id,$type,$where_not_in_tag_ids=array())
    {
        $tag_ids= DB::table('tags')
            ->where('name','like','%'.$search.'%')
            ->pluck('id')
            ->toArray();
        if(empty($tag_ids)){
            return array();
        }
        $tag_ids_of_the_bound_resource=array();
        if($type===1){
            //已绑定具体资源标签Id数组
            $tag_ids_of_the_bound_resource=TagTool::theTagIdsOfTheBoundResource($app_id,1);
        }
        $query= DB::table('tags')
            ->where(array('state'=>1,'app_id'=>$app_id,'tag_type'=>2))
            ->whereIn('id',$tag_ids);
        if(!empty($where_not_in_tag_ids)){
            $query->whereNotIn('id',$where_not_in_tag_ids);
        }
        if(!empty($tag_ids_of_the_bound_resource)){
           $query->whereNotIn('id',$tag_ids_of_the_bound_resource);
        }
        $tags=$query->select('name','id','app_name','description','state','sort_type','app_id')
                    ->get()
                    ->toArray();
        return empty($tags)?array():$tags;
    }

    /***
     * 添加标签
     * @param array $data
     * @return bool
     */
    public function addTag(array $data){
        try{
            $original_image=$data['original_image'];
            $p_tag_ids=$data['p_tag_ids'];
            $data['app_name']=TagTool::getAppNameByAppId($data['app_id']);
            unset($data['original_image']);
            unset($data['p_tag_ids']);
            $img_path='';
            if(!empty($original_image)){
                $img_path=$this->imgTool->imgSave($original_image,2);
            }else{
                return false;
            }
            $data['original_image']=empty($img_path)?'':$img_path;
            DB::beginTransaction();
            $tag_id=$this->saveTagInDB($data);
            if($tag_id===false){
                Log::info('标签保存失败');
                return false;
            }
            if(!empty($p_tag_ids)&&($data['tag_type']==2)){
                foreach ($p_tag_ids as $p_tag_id){
                    $tag_sub_tag_map['tag_id']=$p_tag_id;
                    $tag_sub_tag_map['sub_tag_id']=$tag_id;
                    $tag_sub_tag_map['is_show']=1;
                    $res=$this->saveTagSubTagMapsInDB($tag_sub_tag_map);
                }
            }
            if(($data['tag_type']==1)&&($data['app_id']==2)){
                $resource_ids=ProductTempTool::getAllProductTempIds(1);
                foreach ($resource_ids as $resource_id){
                    $tag_resource_map=array();
                    $tag_resource_map['tag_id']=$tag_id;
                    $tag_resource_map['resource_id']=$resource_id;
                    $tag_resource_map['app_id']=$data['app_id'];
                    TagTool::saveTagResourceMaps($tag_resource_map);
                }
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /****
     * 更新标签
     * @param array $data
     * @return bool
     */
    public function updateTag(array $data){
        try{
            $original_image=$data['original_image'];
            $p_tag_ids=$data['p_tag_ids'];
            $data['app_name']=TagTool::getAppNameByAppId($data['app_id']);
            unset($data['original_image']);
            unset($data['p_tag_ids']);
            $img_path='';
            if(!empty($original_image)){
                $img_path=$this->imgTool->imgSave($original_image,2);
                $data['original_image']=empty($img_path)?'':$img_path;
            }
            DB::beginTransaction();
            $tag_id=$this->saveTagInDB($data);
            if($tag_id===false){
                Log::info('标签保存失败');
                return false;
            }
            $this->delTagSubTagMapsBySubTagId($tag_id);
            $this->deleteTagTempMapByTagId($tag_id);
            if(!empty($p_tag_ids)&&($data['tag_type']==2)){
                foreach ($p_tag_ids as $p_tag_id){
                    $tag_sub_tag_map['tag_id']=$p_tag_id;
                    $tag_sub_tag_map['sub_tag_id']=$tag_id;
                    $tag_sub_tag_map['is_show']=1;
                    $this->saveTagSubTagMapsInDB($tag_sub_tag_map);
                }
            }
            if(($data['tag_type']==1)&&($data['app_id']==2)){
                $resource_ids=ProductTempTool::getAllProductTempIds(1);
                foreach ($resource_ids as $resource_id){
                    $tag_resource_map=array();
                    $tag_resource_map['tag_id']=$tag_id;
                    $tag_resource_map['resource_id']=$resource_id;
                    $tag_resource_map['app_id']=$data['app_id'];
                    TagTool::saveTagResourceMaps($tag_resource_map);
                }
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }
    /***
     * 保存标签
     * @param array $tag
     * @return bool
     */
    public function saveTagInDB(array $tag){
        try{
          $id=isset($tag['id'])?$tag['id']:0;
          $tag['state']=1;
          $tag['updated_at']=time();
          if($id===0){
              $tag['created_at']=time();
              $tag_id=DB::table('tags')->insertGetId($tag);
              return $tag_id;
          }else{
              $res=DB::table('tags')->where(array(
                  'id'=>$id
              ))->update($tag);
              return ($res===0)?false:$id;
          }
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 子标签绑定父级别标签
     * @param array $tag
     * @return bool
     */
    public function saveTagSubTagMapsInDB(array $tag){
            $tag_id=$tag['tag_id'];
            $sub_tag_id=$tag['sub_tag_id'];
            $tag['state']=1;
            $tag['updated_at']=time();
            $exist=TagTool::tagSubTagMapsRecordExistByTagIdAndSubTagId($tag_id,$sub_tag_id,0);
            if($exist){
                $res=DB::table('tag_sub_tag_maps')->where(array(
                    'tag_id'=>$tag_id,
                    'sub_tag_id'=>$sub_tag_id,
                ))->update($tag);
            }else{
                $tag['created_at']=time();
                $res=DB::table('tag_sub_tag_maps')->insert($tag);
            }
            return ($res===0)?false:true;
    }

    /***
     * 删除标签绑定下的子标签
     * @param $tag_id
     * @return bool
     */
    public function delTagSubTagMapsByTagId($tag_id){
        if(empty($tag_id)||!is_int($tag_id)){
            return false;
        }
        $res=DB::table('tag_sub_tag_maps')
            ->where(array('state'=>1,'tag_id'=>$tag_id))
        ->update(array(
            'updated_at'=>time(),
            'state'=>0,
        ));
        return ($res===0)?false:true;
    }

    /**
     * 删除标签和标签之间的绑定
     * @param $sub_tag_id
     * @return bool
     */
    public function delTagSubTagMapsBySubTagId($sub_tag_id){
        if(empty($sub_tag_id)||!is_int($sub_tag_id)){
            return false;
        }
        $res=DB::table('tag_sub_tag_maps')
            ->where(array('state'=>1,'sub_tag_id'=>$sub_tag_id))
            ->update(array(
                'updated_at'=>time(),
                'state'=>0,
            ));
        return ($res===0)?false:true;
    }
    /***
     * 查询记录
     * @param $tag_id
     * @param $sub_tag_id
     * @param int $state
     * @return bool
     */
    public function tagSubTagMapExistByTagIdAndSubTagId($tag_id,$sub_tag_id,$state=1){
        if(empty($tag_id)||!is_int($tag_id)||empty($sub_tag_id)||!is_int($sub_tag_id)){
            return false;
        }
        $query=DB::table('tag_sub_tag_maps')
            ->where(array('tag_id'=>$tag_id,'sub_tag_id'=>$sub_tag_id));

        if($state===1){
            $query->where('state',1);
        }
        $num=$query->count();
        return ($num===0)?false:true;
    }

    /***
     * 删除标签
     * @param $id
     * @return bool
     */
    public function delTagById($id){
        try{
            DB::beginTransaction();
            $num=DB::table('tags')
                ->where(array('id'=>$id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            if($num>0){
                $this->deleteTagTempMapByTagId($id);
            }
            return ($num===0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * id删除标签资源绑定
     * @param $id
     * @return bool
     */
    public function deleteTagTempMapById($id){
        if(empty($id)||!is_int($id)){
            return false;
        }
        $num=DB::table('tag_resource_maps')
            ->where(array('id'=>$id,'state'=>1))
            ->update(array(
                'state'=>0,
                'updated_at'=>time()
            ));
        return ($num>0)?true:false;
    }
    /***
     * 删除tag_id下绑定的资源
     * @param $tag_id
     * @return bool
     */
    public function deleteTagTempMapByTagId($tag_id){
        if(empty($tag_id)||!is_int($tag_id)){
            return false;
        }
        $num=DB::table('tag_resource_maps')
            ->where(array('tag_id'=>$tag_id,'state'=>1))
            ->update(array(
                'state'=>0,
                'updated_at'=>time()
            ));
        return ($num>0)?true:false;
    }
    /***
     * 更新资源在标签下的排序
     * @param $id
     * @param $sort
     * @return bool
     */
    public  function updateTagResourceMapSort($id,$sort){
        if(empty($id)||!is_int($id)||empty($sort)||!is_int($sort)){
            return false;
        }
        $num=DB::table('tag_resource_maps')
            ->where(array(
                'id'=>$id,
                'state'=>1,
            ))->update(array(
                'sort'=>$sort,
                'updated_at'=>time(),
            ));
        return empty($num)?false:true;
    }

    /***
     * 资源数组绑定在标签下
     * @param $tag_id  标签编号
     * @param $resource_ids 资源Id数组
     * @param int $app_id   1素材 2 产品模板
     * @return bool
     */
    public function resourceIdsBindingTagByTagId($tag_id,array $resource_ids,$app_id=1){
        try{
            if(empty($tag_id)||!is_int($tag_id)) return false;
            DB::beginTransaction();
            foreach ($resource_ids as $resource_id){
                $tag_resource_map=array();
                $tag_resource_map['tag_id']=$tag_id;
                $tag_resource_map['app_id']=$app_id;
                $tag_resource_map['resource_id']=$resource_id;
                $save_res=TagTool::saveTagResourceMaps($tag_resource_map);
                if(!$save_res){
                    Log::info('资源id:'.$resource_id.'绑定标签id：'.$tag_id.'失败');
                }
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /**
     * 资源Id绑定在所有特殊标签下
     * @param $resource_id
     * @param int $app_id
     * @return bool
     */
    public function resourceIdBindingSpecialTag($resource_id,$app_id=1){
        try{
            if(empty($resource_id)||!is_int($app_id)) return false;
            DB::beginTransaction();
            $tag_ids=TagTool::getSpecialTagIdsByAppId(2);
            foreach ($tag_ids as $tag_id){
                $tag_resource_map=array();
                $tag_resource_map['tag_id']=$tag_id;
                $tag_resource_map['resource_id']=$resource_id;
                $tag_resource_map['app_id']=$app_id;
                TagTool::saveTagResourceMaps($tag_resource_map);
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }
    /**
     * 数据验证
     * @param Request $request
     * @param $check_data
     * @return mixed
     */
    public static function store(Request $request,$check_data)
    {
        $v = Validator::make($request->all(), $check_data);
        return $v;
    }
    /***
     * 更新标签排序
     * @param $id
     * @param $sort
     * @return bool
     */
    public function updateTagSort($id,$sort){
        if(empty($id)||(!is_int($id))||(!is_int($sort))||($sort<0)){
            return false;
        }
        $update_res=  DB::table('tags')->where(array('state'=>1,'id'=>$id))
            ->update(array(
                'sort'=>$sort,
                'updated_at'=>time(),
            ));
        return ($update_res===1)?true:false;
    }
}